#!/usr/bin/env ruby

require 'tempfile'
require 'socket'

ADDR = 'socket'.freeze

def main(gitaly_dir)
  gitaly_dir = File.realpath(gitaly_dir)

  version = IO.popen("#{File.join(gitaly_dir, 'gitaly')} -version").read
  version_from_file = "Gitaly, version #{IO.read(File.join(gitaly_dir, 'VERSION')).strip}"

  # Use start_with? instead of == because the version output could use git describe, if it is a source install
  # eg: Gitaly, version 1.75.0-14-gd1ecb43f
  abort "\ngitaly -version failed" unless version.start_with?(version_from_file)

  Dir.mktmpdir do |dir|
    Dir.chdir(dir)
    File.write(File.join("#{gitaly_dir}/ruby/gitlab-shell", '.gitlab_shell_secret'), 'test_gitlab_shell_token')

    File.write('config.toml', <<~CONFIG
      socket_path = "#{ADDR}"
      bin_dir = "#{gitaly_dir}"

      [[storage]]
      name = "default"
      path = "#{dir}"

      [gitaly-ruby]
      dir = "#{gitaly_dir}/ruby"

      [gitlab-shell]
      dir = "#{gitaly_dir}/ruby/gitlab-shell"

      [gitlab]
      url = 'http://gitlab_url'

      CONFIG
              )

    pid = nil

    begin
      start = Time.now
      pid = spawn(File.join(gitaly_dir, 'gitaly'), 'config.toml')
      wait_connect
      puts
      puts "\n\nconnection established after #{Time.now - start} seconds\n\n"
    ensure
      if pid
        Process.kill("KILL", pid)
        Process.wait(pid)
      end
    end
  end
end

def wait_connect
  repeats = 100
  sleep_time = 0.1

  repeats.times do
    begin
      Socket.unix(ADDR)
      return
    rescue # rubocop:disable Lint/RescueWithoutErrorClass
      print '.'
      sleep(sleep_time)
    end
  end

  puts "failed to connect to gitaly after #{repeats * sleep_time}s"

  abort
end

unless ARGV.count == 1
  abort "Usage: #{$PROGRAM_NAME} GITALY_DIR"
end

main(ARGV.first)
